// pages/my/integral/integral.js
let giftimg = ''
let giftname = ''
let giftint = ''
let giftid = ''
let openid = ''
let userInfo = {}
const db = wx.cloud.database()
import formatTime from '../../../utils/formatTime.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    integral: [],
    showHELPModal: false, //乐豆说明
    showGiftModal: false, //兑换
    giftInfo: [],
    region: [],
    name: '',
    code: 0,
    info: '',
    ph: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._getTotalPoints()
    this._getintInfo(0)
  },
  _getTotalPoints() {
    wx.cloud.callFunction({
      name: 'seek',
      data: {
        $url: 'integral',
      }
    }).then((res) => {
      this.setData({
        totalPoints: res.result[0].totalPoints
      })
    })
  },
  _getintInfo: function (start = 0) {
    wx.cloud.callFunction({
      name: 'seek',
      data: {
        start,
        count: 10,
        $url: 'integrallist',
      }
    }).then((res) => {
      for (let i = 0, len = res.result.length; i < len; i++) {
        res.result[i].createTime = formatTime(new Date(res.result[i].createTime))
      }
      this.setData({
        integral: this.data.integral.concat(res.result)
      })
    })
  },
  scrollToLower: function (e) {
    this._getintInfo(this.data.integral.length)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();

    this.setData({
      integral: []
    })
    this.onLoad()
    setTimeout(() => {
      wx.stopPullDownRefresh()
      wx.hideNavigationBarLoading();
    }, 1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 弹出乐豆说明
  integralhelp: function () {
    this.setData({
      showHELPModal: true
    })
  },

  // 关闭弹出窗口
  hideModal: function () {
    this.setData({
      showHELPModal: false,
      showGiftModal: false,
      showDingDanModal: false
    })
  },
  // 关闭弹出窗口
  hideDingDanModal: function () {
    this.setData({
      showDingDanModal: false,
      showGiftModal: true
    })
  },

  // 获取兑换礼物信息
  _getGiftInfo() {
    db.collection('gift').orderBy('integral', 'asc').get().then((res) => {
      this.setData({
        giftInfo: res.data,
        showGiftModal: true
      })
    })
  },
  // 点击再获取
  intExchange: function () {
    this._getGiftInfo()
  },
  addGift: function (e) {
    // 先判断乐豆够不
    if (e.target.dataset.item.number != 0) {
      if (this.data.totalPoints >= e.target.dataset.item.integral) {
        wx.cloud.callFunction({
          name: "login"
        }).then(res => {
          openid = res.result.userInfo.openId
          console.log("openid",openid)
          db.collection('user').where({
            _id: openid
          }).limit(1).get().then(res => {
            userInfo = res.data[0]
          })
        }).catch(err => {
          console.log(err)
        })
        wx.chooseAddress({
          success: res => {
            this.setData({
              name: res.userName,
              code: res.postalCode,
              region: [res.provinceName, res.cityName, res.countyName],
              info: res.detailInfo,
              ph: res.telNumber
            })
          },
          fail: err => {
            console.log(err)
          }
        })

        this.setData({
          showDingDanModal: true,
          showGiftModal: false,
        })
        giftimg = e.target.dataset.item.fileid,
          giftname = e.target.dataset.item.name,
          giftint = e.target.dataset.item.integral,
          giftid = e.target.dataset.item._id
      } else {
        wx.showToast({
          title: '您的乐豆不足！',
          icon: 'none'
        })
      }
    } else {
      wx.showToast({
        title: '该礼品货储不足！',
        icon: 'none'
      })
    }
  },
  // 修改姓名
  bindnameInput: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  // 修改邮编
  bindcodeInput: function (e) {
    this.setData({
      code: e.detail.value
    })
  },
  // 修改地区
  bindRegionChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  // 修改收货地址
  bindinfoInput: function (e) {
    this.setData({
      info: e.detail.value
    })
  },
  // 修改手机号
  bindphInput: function (e) {
    if (this.checkPhone(e.detail.value)) {
      this.setData({
        ph: e.detail.value
      })
    }
  },
  //checkPhone()方法
  checkPhone: function (data) {
    var reg = /^(((13)|(15)|(17)|(18))\d{9})$/
    return this.check(data, reg, "手机号码输入错误")
  },
  //check()方法
  check: function (data, reg, errMsg) {
    if (!reg.test(data)) {
      wx.showToast({
        title: errMsg,
        icon: 'none',
        duration: 1500
      })
      return false
    }
    return true
  },
  // 确定订单
  addDingDan: function () {
    if (this.data.name != '' && this.data.code != '' && this.data.region != '' && this.data.info != '' && this.checkPhone(this.data.ph)) {
      wx.showLoading({
        title: '加载中...',
      })
      // 扣乐豆
      wx.cloud.callFunction({
        name: 'integral',
        data: {
          openid,
          sense: 5,
          continueDays: -giftint
        }
      }).then((res) => {
        wx.cloud.callFunction({
          name: 'seek',
          data: {
            giftid,
            $url: 'upgift',
          }
        })
        // 增加一条订单数据
        db.collection('DingDan').add({
          data: {
            giftname,
            giftimg,
            giftint,
            username: userInfo.nickName,
            region: this.data.region,
            name: this.data.name,
            code: this.data.code,
            info: this.data.info,
            ph: this.data.ph,
            state: '已提交',
            createTime: db.serverDate(), // 服务端的时间
          }
        }).then((res) => {
          wx.hideLoading()
          this.onPullDownRefresh()
          this.setData({
            showDingDanModal: false
          })
        })
      })
    }
  },
  onPreviewImage(event) {
    // 图片预览
    const ds = event.target.dataset
    wx.previewImage({
      urls: [ds.imgsrc],
      current: ds.imgsrc,
    })
  },
})